# @Version        : 1.0
# @Update Time    : 2024/11/6 23:49
# @File           : role_service.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
from advanced_alchemy import service
from sqlalchemy import and_
from src import models, schemas
from src.core.exception import BaseAppException
from src.crud.role_repository import RoleRepo
from src.crud.menu_repository import MenuRepo
from src.crud.dept_repository import DeptRepo


class RoleService(service.SQLAlchemyAsyncRepositoryService[models.SysRole, RoleRepo]):
    repository_type = RoleRepo

    async def update_role_permissions(self, model: schemas.RolePermissionsSchema):
        # 查询角色
        role = await self.get_one_or_none(
            and_(models.SysRole.id == model.id),
            load=[models.SysRole.menus, models.SysRole.depts],
        )
        if not role:
            raise BaseAppException(msg="角色不存在")
        if role.menus:
            role.menus.clear()
        if model.menu_ids:
            # 查询菜单列表
            menus = await MenuRepo(session=self.repository.session).list(
                and_(models.SysMenu.id.in_(model.menu_ids))
            )
            if menus:
                for menu in menus:
                    role.menus.add(menu)
        if role.depts:
            role.depts.clear()
        if model.dept_ids:
            depts = await DeptRepo(session=self.repository.session).list(
                and_(models.SysDept.id.in_(model.dept_ids))
            )
            if depts:
                for dept in depts:
                    role.depts.add(dept)
        role.home_key = model.home_key
        role.data_scope = model.data_scope
        await self.repository.session.commit()
        return role
